import { NavLink, useLocation, useNavigate } from "react-router-dom"
import './FilmsStyle.sass'
import { useEffect, useReducer, useState } from "react"
import type { FilmListParams } from "../../../../api/Type"
import { getFilmListApi } from "../../../../api"
import type { Action, State } from "../../../../type/HomeType"
import { useSelector } from "react-redux"
import type { FilmState } from "../../../../type/FilmStore"
import LoadingContent from '../../../../components/loadingcontent/LoadingContent'

function FilmsView () {

  // #region 变量声明
  const location = useLocation() // 路由信息
  const [ pageNum, setPageNum ] = useState(1) // 电影列表页码值
  const [ state, dispatch ] = useReducer((prev: State, action: Action): State => {
    const next = { ...prev }
    if (next[action.type] !== undefined) {
      (next[action.type] as typeof action.value) = action.value
    }
    // console.log(next, action.value, next[action.type])
    return next
  }, {
    films: [], // 电影列表
    total: 0 // 电影总数
  })
  const film = useSelector((state: FilmState) => state.film) // 电影状态管理
  const navigate = useNavigate() // 路由
  const [ isBottom, setIsBottom ] = useState(false) // 是否到底了
  const [ type, setType ] = useState(1)
  const [ loading, setLoading ] = useState(true)
  // #endregion

  // #region 函数
  // 获取电影列表
  const getFilmList = async (options: FilmListParams) => {
    try {
      setLoading(true)
      const res = await getFilmListApi(options)
      // console.log(res)
      if (res.data.status === 0) {
        dispatch({ type: 'films', value: [...state.films, ...res.data.data.films] })
        dispatch({ type: 'total', value: res.data.data.total })
        // console.log('res.data.data.total at line 38 in films/FilmsView.tsx:', res.data.data.total)
        // console.log(res.data.data.films, state.films)
      }
      setIsBottom(false) // 获取完数据后标注没有触底
      setLoading(false)
    } catch (error) {
      console.log(error)
      setIsBottom(false)
      setLoading(false)
    }
  }
  // 滚动事件
  const scrollHandler = (e: React.UIEvent<HTMLDivElement>) => {
    const et: HTMLDivElement = e.target as HTMLDivElement
    if (!et.firstElementChild) return
    if (et.scrollTop > 200) {
      et.firstElementChild.classList.add('sticky')
    } else {
      et.firstElementChild.classList.remove('sticky')
    }
    // console.log(et.scrollHeight)
    if (isBottom) return
    if (et.scrollTop > et.scrollHeight - et.clientHeight - 40) {
      setIsBottom(true)
      // console.log('到底了')
      // 触底换页
      const maxPage = Math.ceil(state.total / 10) // 最大页码值
      // console.log('state.total at line 61 in films/FilmsView.tsx:', state.total)
      // console.log('maxPage at line 61 in films/FilmsView.tsx:', maxPage)
      setPageNum(Math.max(Math.min(maxPage, pageNum + 1), 1))
    }
    // console.log(et)
  }
  // 时间处理
  const formatTime = (time: number) => {
    const date = new Date(time)
    const res =  date.toLocaleDateString('zh-CN', {
      year: '2-digit', // 添加年份显示
      month: 'numeric',
      day: 'numeric',
      weekday: 'long',
    }).slice(3).replace('星期', '周')
    return res.slice(-2) + ' ' + res.slice(0, -2)
  }
  // 跳转到电影详情页面
  const toFilmDetail = (filmId: number) => {
    navigate('/film/' + filmId)
  }
  // #endregion

  // #region Hooks
  // 路由改变重置页码值
  useEffect(() => {
    setIsBottom(true)
    setPageNum(1)
    // 清空films
    dispatch({ type: 'films', value: [] })
    setType(location.pathname === '/home/films/nowPlaying' ? 1 : 2)
    // console.log(state.films)
    // console.log('location改变了')
  }, [location])
  useEffect(() => {
    // console.log('pageNum at line 100 in films/FilmsView.tsx:', pageNum)
    getFilmList({ type, pageSize: 10, pageNum, cityId: film.cityId || 110100 })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [type, pageNum, film.cityId])
  // #endregion

  return (
    <div className="films" onScroll={ scrollHandler }>
      <div className="tabs">
        <NavLink to="/home/films/nowPlaying">正在热映</NavLink>
        <NavLink to="/home/films/comingSoon">即将上映</NavLink>
      </div>
      <div className="content">
        <LoadingContent loading={ loading } />
        { state.films.map((item) => (
          <div className="item" key={ item.filmId } onClick={ () => toFilmDetail(item.filmId) }>
            <img src={ item.poster } />
            <div className="title">{ item.name }<span>{ item.filmType.name }</span></div>
            <button className={ location.pathname === '/home/films/nowPlaying' ? 'nowPlaying' : 'comingSoon' }>
              { location.pathname === '/home/films/nowPlaying' ? '购票' : '预购' }
            </button>
            <div className="grade">
              { item.grade ? (<>观众评分<span>{ item.grade }</span></>) : '' }
            </div>
            <div className="actors">主演：{ item.actors.map(v => v.name).join(' ') }</div>
            <div className="time">
              {
                location.pathname === '/home/films/nowPlaying'
                  ? <>{ item.nation } | { item.runtime }分钟</>
                  : <>上映时间：{ formatTime(item.premiereAt * 1000) }</>
              }
            </div>
          </div>
        )) }
      </div>
    </div>
  )
}

export default FilmsView
